import { NavBar } from '@nutui/nutui-react';
import { ArrowLeft } from '@nutui/icons-react'
import { SmileOutline } from 'antd-mobile-icons'
import { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { format } from 'date-fns'
import $ from '../axios'
import { setLastExpressions } from '../store/index'
import { debounce } from 'lodash'
import './chat.css'
import 'animate.css';
export default function Xiang() {
    const Navigate = useNavigate()
    const [list, setList] = useState([])
    const data = useSelector(data => {
        return data.chat
    })
    const lastExpressions = useSelector(data => { return data.lastExpressions })
    const inputRef = useRef()
    const buttonRef = useRef()
    const Myid = useSelector(data => { return data.Myid })
    const Send = async (value) => {
        let newData = {
            content: value,
            acceptId: data._id,
            sendId: Myid
        }
        await $.post('/sendChat', newData).then(val => {
            setList(val.data.data)
        })
    }

    // 防抖方法
    const debounceSend = debounce((val) => {
        Send(val)
    }, 300)

    const getList = async () => {
        await $.get('/getChat').then(val => {
            setList(val.data.data)
        })
    }
    useEffect(() => {
        getList()
        // 实例化websocket
        var socket = new WebSocket('ws://localhost:4000')
        // 连接后端
        socket.addEventListener('open', () => {
            console.log('连接成功了');
        })
        // 键盘回车事件
        inputRef.current.addEventListener('keydown', (e) => {
            if (e.keyCode === 13 & inputRef.current.value != '') {

                debounceSend(inputRef.current.value)
                socket.send(inputRef.current.value)
                inputRef.current.value = ''
            }
        })
        // 点击发送消息
        buttonRef.current.addEventListener('click', () => {
            debounceSend(inputRef.current.value)
            socket.send(inputRef.current.value)
            inputRef.current.value = ''
        })
        // 监听发送的数据
        socket.addEventListener('message', (e) => {
            let data = JSON.parse(e.data)
            if (data.type === 'MESSAGE') {
                getList()
            }
        })
    }, [])
    const Expressions = ['&#128512;', '&#128542;', '&#10084', '&#128079;',
        "&#128512;", "&#128542;", "&#10084;", "&#128079;", "&#128514;",
        "&#128148;", "&#128176;", "&#128293;", "&#128170;", "&#9996;",
        "&#128064;", "&#128161;", "&#9889;", "&#9728;", "&#9748;",
        "&#128562;", "&#128054;", "&#128049;", "&#128055;", "&#128047;", "&#128059;", "&#128053;",
        "&#128021;", "&#128008;", "&#128038;", "&#128020;", "&#129416;",
        "&#128013;", "&#128051;", "&#128044;",
        "&#129419;", "&#128027;", "&#129410;", "&#128028;", "&#128029;",
        "&#128375;", "&#129415;", "&#128010;", "&#129408;", "&#129419;",
        "&#128512;", "&#128542;", "&#10084;", "&#128079;", "&#128514;",]
    const [showExpression, setShowExpression] = useState(false)
    const dispatch = useDispatch()
    return (
        <div>
            <NavBar
                fixed={true}
                back={
                    <>
                        <ArrowLeft />{data.name}
                    </>
                }
                onBackClick={(e) => Navigate('/Chat')}>
            </NavBar>
            <div className='chat'>
                {list.map(ele => {
                    return <div key={ele._id}>
                        {ele.sendId._id === data._id && ele.acceptId._id === Myid ?
                            <div>
                                <div className='he'>
                                    <img src={ele.sendId.img} alt='' height={50} width={50} style={{ borderRadius: '50%' }}></img>
                                    {ele.content.includes(';')
                                        ? <button className='heContent' dangerouslySetInnerHTML={{ __html: ele.content }}></button>
                                        : <button className='heContent'>{ele.content}</button>}
                                </div>
                                <div style={{ height: '20px', width: '80px', marginLeft: '19%', marginTop: '-5px' }}>
                                    {format(ele.time, 'MM-dd HH:mm')}
                                </div>
                            </div>
                            : ''}
                        {ele.sendId._id === Myid && ele.acceptId._id === data._id ?
                            <div>
                                <div className='me'>
                                    {ele.content.includes(';')
                                        ? <button className='meContent' dangerouslySetInnerHTML={{ __html: ele.content }}></button>
                                        : <button className='meContent'>{ele.content}</button>}
                                    <img src={ele.sendId.img} alt='' height={50} width={50} className='meImg' style={{ borderRadius: '50%' }}></img>
                                </div>
                                <div style={{ marginLeft: '65%', height: '80px', width: '80px' }}>
                                    {format(ele.time, 'MM-dd HH:mm')}
                                </div>
                            </div>
                            : ''}
                    </div>
                })}
            </div>
            <div style={{
                display: showExpression ? '' : 'none',
                top: '64%', position: 'fixed', height: '260px', width: '260px',
                backgroundColor: 'rgb(243,242,242)', borderRadius: '10px'
            }}>
                <p style={{ color: 'gray' }}>最近使用</p>
                <div className='RecentlyUsed'>
                    {lastExpressions.map((emo, index) => {
                        return <span key={index} style={{ fontSize: '16px' }}
                            onClick={() => {
                                Send(emo)
                                dispatch(setLastExpressions(emo))
                                setShowExpression(false)
                            }}
                            dangerouslySetInnerHTML={{ __html: emo }}></span>
                    })}
                </div>
                <p style={{ color: 'gray' }}>全部表情</p>
                <div className='Allexpressions'>
                    {Expressions.map((emo, index) => {
                        return <span key={index} style={{ fontSize: '16px' }}
                            onClick={() => {
                                Send(emo)
                                dispatch(setLastExpressions(emo))
                                setShowExpression(false)
                            }}
                            dangerouslySetInnerHTML={{ __html: emo }}></span>
                    })}
                </div>
                <div className='expression1'></div>
            </div>
            <div style={{ display: 'flex', position: 'fixed', top: '94%', width: '100%', height: '6%', backgroundColor: 'white' }}>
                <SmileOutline onClick={() => setShowExpression(!showExpression)} style={{ marginTop: '3%', marginLeft: '5%', fontSize: '30px' }} />
                <input clearable='true' placeholder='快开始吧！' ref={inputRef}
                    style={{
                        paddingLeft: '10px', fontSize: '17px', backgroundColor: 'rgb(247,249,255)',
                        border: '0', marginTop: '2%', height: '70%', color: 'black', marginLeft: '4%', width: '70%'
                    }}></input>
                <div style={{ height: '100%', lineHeight: '60px', width: '85px' }}>
                    <p style={{ color: 'green', fontSize: '20px', textAlign: 'center' }} ref={buttonRef}>发送</p>
                </div>
            </div>
        </div>
    )
}